<?php
namespace app\common\service\wx;
use app\common\service\wx\WXBizDataCrypt;
use app\common\service\wx\ErrorCode;
class Program{
	protected $appid="wx17a79f4aac30177e";
	protected $secret="dd360e7d73214b13992e8362180ae81c";
	protected $loginUrl="https://api.weixin.qq.com/sns/jscode2session?";
	protected $grant_type="authorization_code";
	/**
	 * 获取到sessiokey等
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function code2Session($param){
		$requestUrl=$this->loginUrl."appid=".$this->appid."&secret=".$this->secret."&js_code=".$param['code']."&grant_type=".$this->grant_type;
		$requestData=$this->https_curl($requestUrl);
		return $requestData;
	}
	/**
	 * 对加密的电话号码包等进行解密
	 * @param  [type] $pram [description]
	 * @return [type]       [description]
	 */
	public function decodeParam($param){
		$returnData=[];
		/*$sessionKey = str_replace(' ','+',$param['sessionKey']);
		$encryptedData=str_replace(' ','+',$param['encryptedData']);
		$iv=str_replace(' ','+',$param['iv']);*/
		$sessionKey =$param['sessionKey'];
		$encryptedData=$param['encryptedData'];
		$iv=$param['iv'];
		/*$sessionKey =urldecode($param['sessionKey']);
		$encryptedData=urldecode($param['encryptedData']);
		$iv=urldecode($param['iv']);*/
		$errCode = $this->decryptData($encryptedData, $iv,$sessionKey, $data);
		$returnData['errCode']=$errCode;
		$returnData['data']=json_decode($data,true);
		return $returnData;
	}
	/**
	 * 检验数据的真实性，并且获取解密后的明文.
	 * @param $encryptedData string 加密的用户数据
	 * @param $iv string 与用户数据一同返回的初始向量
	 * @param $data string 解密后的原文
     *
	 * @return int 成功0，失败返回对应的错误码
	 */
	public function decryptData( $encryptedData, $iv,$sessionKey, &$data )
	{
		if (strlen($sessionKey) != 24) {
			return ErrorCode::$IllegalAesKey;
		}
		$aesKey=base64_decode($sessionKey);
		if (strlen($iv) != 24) {
			return ErrorCode::$IllegalIv;
		}
		$aesIV=base64_decode($iv);
		$aesCipher=base64_decode($encryptedData);
		$result=openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
		$dataObj=json_decode( $result );
		if( $dataObj  == NULL )
		{
			return ErrorCode::$IllegalBuffer;
		}
		if( $dataObj->watermark->appid != $this->appid )
		{
			return ErrorCode::$IllegalBuffer;
		}
		$data = $result;
		return ErrorCode::$OK;
	}
	
	protected  function https_curl($url, $data = null,$method="get"){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);//https请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        switch ($method) {
            case 'get':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
                curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept-Charset: utf-8"));
                curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
                curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                break;
            case 'put':
                $data = json_encode($data);
                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
                curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
            case 'post':
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST,"POST"); //设置请求方式
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                break;
            case 'delete':
                //$data  = json_encode($data);
                curl_setopt ($curl, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
                curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt ($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,true);
    }
}